package com.net;

import android.text.TextUtils;
import android.widget.Toast;

import com.base.App;
import com.event.PageEvent;
import com.widget.PageLayout;

import org.greenrobot.eventbus.EventBus;

import java.io.IOException;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import retrofit2.HttpException;

public abstract class RxResponseObserver<T> implements Observer<T> {
    @Override
    public void onSubscribe(Disposable d) {

    }

    @Override
    public void onNext(T t) {
        onSuccess(t);
    }

    @Override
    public void onError(Throwable e) {
        onFail(e);
    }

    @Override
    public void onComplete() {

    }

    public abstract void onSuccess(T t);
    public void onFail(Throwable e){
        String errorMsg;
        if (e instanceof IOException) {
            /** 没有网络 */
            errorMsg = "Please check your network status";
            EventBus.getDefault().post(new PageEvent(PageLayout.NO_NET, "网络异常，点击重试"));
        } else if (e instanceof HttpException) {
            /** 网络异常，http 请求失败，即 http 状态码不在 [200, 300) 之间, such as: "server internal error". */
            errorMsg = ((HttpException) e).response().message();
            EventBus.getDefault().post(new PageEvent(PageLayout.NO_NET, "网络异常，http 请求失败"));
        }  else {
            /** 其他未知错误 */
            errorMsg = !TextUtils.isEmpty(e.getMessage()) ? e.getMessage() : "unknown error";
            EventBus.getDefault().post(new PageEvent(PageLayout.ERROR, "其他未知错误"));
        }

        Toast.makeText(App.getAppContext(),errorMsg,Toast.LENGTH_SHORT).show();
    }
}
